<?php

// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------


namespace app\index\controller;

use app\index\BaseController;
use app\index\model\charge\ChargePileGun;
use app\index\model\charge\ChargingStation;
use app\index\model\charge\PileClient;
use app\index\model\common\SystemConfig;
use app\index\model\order\OrderStatus;
use app\index\model\order\PileOrder;
use app\index\model\order\PileOrderInfo;
use app\index\model\order\PileOrderMoney;
use app\index\model\order\PileOrderSon;
use app\index\model\user\UserBill;
use app\index\model\user\UserCar;
use app\index\model\user\UserPileCost;
use app\index\model\user\WechatUser;
use app\service\weChat\WeChatAppletService;
use function EasyWeChat\Kernel\Support\generate_sign;
use EasyWeChat\Kernel\Support\XML;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;
use app\index\model\charge\ChargePile;
use app\worker\Events;
use app\index\model\user\User;

/**
 * Class Auth
 * @package app\controller\api
 * @author xaboy
 * @day 2020-05-06
 */
class Order extends BaseController
{

    /**
     * 查询订单是不是充电状态
     * @return Order
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function selectOrderCharge(){
        return $this->selectOrderStatus([1],0,'正在启动充电中，请稍后……');
    }

    /**
     * 获取订单状态
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function selectOrderStatus($orderStatus,$errorStatus,$errorMsg){
        $userId = $this->request->uid();
        $getData = Request::post();
        if(!$getData['order_id']) return $this->fail('请选择要查看的订单');
        $pileOrderModel = new PileOrder();
        $orderInfo = $pileOrderModel->getInfoById($getData['order_id'],['uid'=>$userId]);
        if(!$orderInfo) return $this->fail('请选择正确的订单');
        $statusName = config('index.order_status_name');
        if(!isset($statusName[$orderInfo['status']])){
            $orderInfo['status_name'] = '订单异常';
        }else{
            $orderInfo['status_name'] = $statusName[$orderInfo['status']];
        }
        if($orderInfo['status']==$errorStatus){
            return $this->fail($errorMsg);
        }elseif(in_array($orderInfo['status'],$orderStatus)){
            return $this->success($statusName[$orderInfo['status']]);
        }else{
            return $this->fail($statusName[$orderInfo['status']]);
        }
    }

    /**
     * 获取充电中的订单信息
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function getChargeOrderInfo(){
        $userId = $this->request->uid();
        $pileOrderModel = new PileOrder();
        $orderInfo = $pileOrderModel->getUserChargeOrderInfo($userId);
        if(!$orderInfo) return $this->fail('当前没有充电订单');
        //获取其他信息
        $chargePileModel = new ChargePile();
        $pileInfo = $chargePileModel->getInfoById($orderInfo['pile_id'],'id,device_sn,number_sn');
        $chargingStationModel = new ChargingStation();
        $stationInfo = $chargingStationModel->getInfoById($orderInfo['station_id'],'id,title');
        $userCarModel = new UserCar();
        $cardInfo = $userCarModel->getInfoById($orderInfo['car_id'],['user_id'=>$userId],'id,car_number');
        $backData = [
            'order_id'=> $orderInfo['id'],//对应的充电订单id
            'order_sn'=> $orderInfo['order_sn'],//对应的充电订单编号
            'pile_id'=> $orderInfo['pile_id'],//充电桩id
            'gun_id'=> $orderInfo['gun_id'],//充电枪id
            'station_name'=> isset($stationInfo['title']) ? $stationInfo['title'] : '',//充电站名称
            'pile_number'=> isset($pileInfo['device_sn']) ? $pileInfo['device_sn'] : '',//充电桩编号
            'card_number'=>  isset($cardInfo['car_number']) ? $cardInfo['car_number'] : '',//汽车车牌号

        ];
        //获取子订单信息
        $orderSonModel = new PileOrderSon();
        $orderSonInfo = $orderSonModel->getLastOrderSonInfo($orderInfo['id']);
        //dump($orderSonInfo);
        //不存在订单记录
        if(!$orderSonInfo){
            $backData['charge_time'] = '获取数据中';//累计充电时间
            $backData['residue_time'] =  '获取数据中';//剩余时间
            $backData['charge_number'] =  '获取数据中';//充电度数
            $backData['charged_amount'] = '计算中';//已充电的金额
            $backData['out_voltage'] =  '获取数据中';//输出电压
            $backData['out_electric'] =  '获取数据中';//输出电流
            $backData['residue_time'] =  '获取数据中';//剩余时间
        }else{
            if($orderSonInfo['type'] == 1){
                $getInfo = json_decode($orderSonInfo['content_data'],true);
                $backData['charge_time'] = $orderSonInfo['charge_time'];//累计充电时间
                $backData['residue_time'] = $orderSonInfo['residue_time'];//剩余时间
                $backData['charge_number'] = $orderSonInfo['charge_number'];//充电度数
                $backData['charged_amount'] = number_format($orderSonInfo['charged_amount'],2);//已充电的金额
                $backData['out_voltage'] = isset($getInfo['out_voltage']) ? bcmul($getInfo['out_voltage'],1,2) : '获取中';//输出电压
                $backData['out_electric'] = isset($getInfo['out_electric']) ? bcmul($getInfo['out_electric'],1,3) : '获取中';//输出电流
                $backData['residue_time'] = $orderSonInfo['residue_time'];//剩余时间
            }else if($orderSonInfo['type'] == 2){
                $getInfo = json_decode($orderSonInfo['content_data'],true);
                $backData['charge_time'] = $orderSonInfo['charge_time'];//累计充电时间
                $backData['residue_time'] = $orderSonInfo['residue_time'];//剩余时间
                $backData['charge_number'] = $orderSonInfo['charge_number'];//充电度数
                $backData['charged_amount'] = '计算中';//已充电的金额
                $backData['out_voltage'] = bcmul($getInfo['pile_voltage_out'],1,2);//输出电压
                $backData['out_electric'] = bcmul($getInfo['pile_electric_out'],1,3);//输出电流
                $backData['residue_time'] = $orderSonInfo['residue_time'];//剩余时间
            }else{
                $backData['charge_time'] = '获取数据中';//累计充电时间
                $backData['residue_time'] =  '获取数据中';//剩余时间
                $backData['charge_number'] =  '获取数据中';//充电度数
                $backData['charged_amount'] = '计算中';//已充电的金额
                $backData['out_voltage'] =  '获取数据中';//输出电压
                $backData['out_electric'] =  '获取数据中';//输出电流
                $backData['residue_time'] =  '获取数据中';//剩余时间
            }
        }
        return $this->success('获取成功',$backData);
    }

    /**
     * 结束充电
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function endChargingOrder(){
        $getData = Request::post();
        if(!$getData['order_id']) return $this->fail('请选择要结束充电的充电记录');
        if(!$getData['gun_id']) return $this->fail('请选择要结束充电的充电枪');
        if(!$getData['pile_id']) return $this->fail('请选择要结束充电的充电桩');
        $pileOrderModel = new PileOrder();
        $orderInfo = $pileOrderModel->getInfoById($getData['order_id']);
        if(!$orderInfo) return $this->fail('请选择正确的充电订单');
        $userId = $this->request->uid();
        if($orderInfo['uid'] != $userId)  return $this->fail('请选择正确的充电订单');
        if($orderInfo['pile_id'] != $getData['pile_id']) return $this->fail('请选择正确的充电桩');
        if($orderInfo['gun_id'] != $getData['gun_id']) return $this->fail('请选择正确的充电枪');
        if($orderInfo['status'] == 1){
            //获取充电桩
            $chargePileModel = new ChargePile();
            $pileInfo = $chargePileModel->getInfoById($getData['pile_id']);
            if(!$pileInfo) return $this->fail("选择充电桩不存在");
            //获取充电枪
            $chargePileGunModel = new ChargePileGun();
            $gunWhere = ['id'=>$getData['gun_id'],'pile_id'=>$getData['pile_id']];
            $getGunInfo = $chargePileGunModel->getGunInfoByWhere($gunWhere,'id,pile_id,is_status,error_remark,num');
            if(!$getGunInfo) return $this->fail("选择充电枪不存在");
            //获取当前设备是否处于链接状态
            $pileClientModel = new PileClient();
            $pileClientInfo = $pileClientModel->getInfoByPileId($getData['pile_id']);
            //添加操作记录
            $orderStatusModel = new OrderStatus();
            $billId = $orderStatusModel->addInfo($orderInfo,9,'用户结束充电操作');
            $sendData = ['pile_gun'=>$getGunInfo];
            $sentResult = Events::sendMsg($pileInfo,$pileClientInfo,$sendData,'platformStopCharge');
            //$sentResult['code'] = 0;
            if($sentResult['code'] == 0){
                return $this->success('正在停止充电中，请稍后……',['order_id'=>$orderInfo['id']]);
            }else{
                return $this->fail("停止充电失败，请稍后重试");
            }
        }else{
            return $this->fail('当前充电记录不是处在充电状态中，不能结束充电');
        }
    }

    /**
     * 查询订单是不是已经结束充电状态
     * @return Order
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function selectOrderChargeStop(){
        return $this->selectOrderStatus([2,3,4,5,6],1,'正在停止充电中，请稍后……');
    }

    /**
     * 获取订单详情
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function getOrderInfo(){
        $getData = Request::post();
        if(!$getData['order_id']) return $this->fail('请选择充电记录');
        $pileOrderModel = new PileOrder();
        $orderField = 'id,uid,order_sn,order_number,pile_id,station_id,pile_gun_number,gun_id,charge_time,charge_number,
        loss_number,start_time,end_time,charge_cost,service_cost,peak_electric_cost,peak_service_cost,flat_electric_cost,
        flat_service_cost,valley_electric_cost,valley_service_cost,cost_id,cost_content,total_price,pile_price,pay_price,
        paid,pay_time,pay_type,status,mark,remark,return_confirm_time,third_sn,create_time,car_id,is_verify';
        $orderInfo = $pileOrderModel->getInfoById($getData['order_id'],[],$orderField);
        if(!$orderInfo) return $this->fail('请选择正确的充电订单');
        $userId = $this->request->uid();
        if($orderInfo['uid'] != $userId)  return $this->fail('请选择正确的充电订单');
        //设置订单其他参数
        $chargePileModel = new ChargePile();
        $pileInfo = $chargePileModel->getInfoById($orderInfo['pile_id'],'id,device_sn,number_sn');
        $chargingStationModel = new ChargingStation();
        $stationInfo = $chargingStationModel->getInfoById($orderInfo['station_id'],'id,title');
        $userCarModel = new UserCar();
        $cardInfo = $userCarModel->getInfoById($orderInfo['car_id'],['user_id'=>$userId],'id,car_number');
        $orderInfo['station_name'] = isset($stationInfo['title']) ? $stationInfo['title'] : '';//充电站名称
        $orderInfo['pile_number'] = isset($pileInfo['number_sn']) ? $pileInfo['number_sn'] : '';//充电桩编号
        $orderInfo['card_number'] =  isset($cardInfo['car_number']) ? $cardInfo['car_number'] : '';//汽车车牌号

        //订单处于充电结束之前的状态
        $statusName = config('index.order_status_name');
        if($orderInfo['status'] < 2 && $orderInfo['status'] >= 0){
            if(!isset($statusName[$orderInfo['status']])){
                $orderInfo['status_name'] = '订单异常';
            }else{
                $orderInfo['status_name'] = $statusName[$orderInfo['status']];
            }
            unset($orderInfo['charge_hand_content']);
            unset($orderInfo['cost_id']);
            return $this->success('获取订单信息成功',$orderInfo);
        }else{
            //未计算订单金额
            if($orderInfo['is_verify'] == 0 && $orderInfo['status'] >= 2){
                /*
                //充电时间、充电度数、充电损耗统计
                $orderInfoModel = new PileOrderInfo();
                $orderDetails = $orderInfoModel->getOrderInfo($orderInfo['id']);
                if(!$orderDetails) return $this->fail('等待订单数据确认');
                $orderSonModel = new PileOrderSon();
                $orderSonList = $orderSonModel->getLastOrderSonList($orderInfo['id'],1,2);
                $infoTimeCount = strtotime($orderDetails['end_time']) - strtotime($orderDetails['start_time']);
                $infoElectric = $orderDetails['all_electric'] + $orderDetails['all_loss_electric'];
                $setOrderData = ['status'=>3,'update_time'=>date("Y-m-d H:i:s"),'is_verify'=>1];
                //存在着对应的充电记录
                if(isset($orderSonList[0])){
                    $sonTimeCount = $orderSonList[0]['charge_time'];
                    $sonElectric = $orderSonList[0]['charge_number'] + $orderSonList[0]['loss_number'];
                    $getSonInfo = json_decode($orderSonList[0]['content_data'],true);
                    $changeElectric = 0;
                    if($orderSonList[0]['type'] == 1){
                        $changeElectric = $getSonInfo['out_voltage'] * $getSonInfo['out_electric'] * 10 * 20;
                    }else if($orderSonList[0]['type'] == 2){
                        $changeElectric = $getSonInfo['pile_voltage_out'] * $getSonInfo['pile_electric_out'] * 10 * 20;
                    }
                    $differenceElectric = $infoElectric - $sonElectric;
                    //交易数据正常 结算记录的充电的总电量大于上条记录的总电流
                    if($changeElectric > 0 && $infoElectric > $sonElectric && $differenceElectric < $changeElectric){
                        if($sonTimeCount > $infoTimeCount) $infoTimeCount = $sonTimeCount;
                        $setOrderData['all_electric'] = $infoElectric;//总的充电电量
                        $setOrderData['charge_number'] = $orderDetails['all_electric'];//充电电量
                        $setOrderData['loss_number'] = $orderDetails['all_loss_electric'];//计损总电量
                        $setOrderData['charge_time'] = $infoTimeCount;//总的充电时间
                        //统计订单的金额
                        $getMoneyInfo = $this->countOrderMoney($orderInfo,$orderDetails,$setOrderData);
                    //交易数据未达到指定的条件
                    }else{
                        if(isset($orderSonList[1])){
                            //第二条记录的充电时间大于第一条
                            if($sonTimeCount < $orderSonList[1]['charge_time']) $sonTimeCount = $orderSonList[1]['charge_time'];
                            //第二条的充电总量大于第一条
                            if($sonElectric < ($orderSonList[1]['charge_number'] + $orderSonList[1]['loss_number'])){
                                $sonElectric = $orderSonList[1]['charge_number'] + $orderSonList[1]['loss_number'];
                                $orderSonList[0]['charge_number'] = $orderSonList[1]['charge_number'];
                                $orderSonList[0]['loss_number'] = $orderSonList[1]['loss_number'];
                            }
                        }
                        $setOrderData['all_electric'] = $sonElectric;//总的充电电量
                        $setOrderData['charge_number'] = $orderSonList[0]['charge_number'];//充电电量
                        $setOrderData['loss_number'] = $orderSonList[0]['loss_number'];//计损总电量
                        $setOrderData['charge_time'] = $sonTimeCount;//总的充电时间
                        //统计订单的金额
                        $setOrderDetails = $this->setElectricNumber($orderInfo,$setOrderData,$orderSonList[0]);
                        $getMoneyInfo = $this->countOrderMoney($orderInfo,$setOrderDetails,$setOrderData);
                    }
                }else{
                    $setOrderData['all_electric'] = $infoElectric;//总的充电电量
                    $setOrderData['charge_number'] = $orderDetails['all_electric'];//充电总电量
                    $setOrderData['loss_number'] = $orderDetails['all_loss_electric'];//计损总电量
                    $setOrderData['charge_time'] = $infoTimeCount;//总的充电时间
                    //统计订单的金额
                    $getMoneyInfo = $this->countOrderMoney($orderInfo,$orderDetails,$setOrderData);
                }
                $PileOrderMoney = new PileOrderMoney();
                Db::startTrans();
                $orderResult = $pileOrderModel->updateOrder($getData['order_id'],$getMoneyInfo['save_order_info']);
                $orderMoneyResult = $PileOrderMoney->addInfo($getMoneyInfo['order_money_data']);
                if($orderResult && $orderMoneyResult){
                    Db::commit();
                }else{
                    Db::rollBack();
                    return $this->fail('等待订单数据确认');
                }
                */
                $serMoneyResult = $this->setOrderPayInfo($pileOrderModel,$orderInfo,'获取订单详情统计金额');
                if($serMoneyResult['code'] > 0){
                    return $this->fail($serMoneyResult['msg'],100);
                }
                $orderInfo = $pileOrderModel->getInfoById($getData['order_id'],[],$orderField);
            }
            //默认余额支付开启
            $systemConfigModel = new SystemConfig();
            $defaultBalancePayStatus = $systemConfigModel->getValueByKey('default_balance_pay_status');
            if($defaultBalancePayStatus && $orderInfo['status'] == 3 && $orderInfo['paid'] == 0 && $orderInfo['is_verify'] == 1){
                $userModel = new User();
                $userInfo = $userModel->getUserInfoById($orderInfo['uid']);
                if($userInfo && $userInfo['now_money'] >= $orderInfo['pay_price']){
                    $this->balancePay([],$orderInfo,$orderInfo['uid'],0);
                    $orderInfo = $pileOrderModel->getInfoById($getData['order_id'],[],$orderField);
                }
            }
            //返回数据
            $orderInfo['station_name'] = isset($stationInfo['title']) ? $stationInfo['title'] : '';//充电站名称
            $orderInfo['pile_number'] = isset($pileInfo['device_sn']) ? $pileInfo['device_sn'] : '';//充电桩编号
            $orderInfo['card_number'] =  isset($cardInfo['car_number']) ? $cardInfo['car_number'] : '';//汽车车牌号
            unset($orderInfo['charge_hand_content']);
            unset($orderInfo['cost_content']);
            unset($orderInfo['cost_id']);
            $payTypeName = config('add.pay_type_name');
            $orderInfo['type_name'] = $payTypeName[$orderInfo['pay_type']];
            $orderInfo['user_pay_pwd'] = $this->userPayPwdStatus();
            return $this->success('获取订单信息成功',$orderInfo);
        }
    }

    /**
     * 订单金额统计
     * @param $orderInfo
     * @param $orderDetails
     * @param $setOrderData
     * @return array
     */
    function countOrderMoney($orderInfo,$orderDetails,$setOrderData){
        $saveOrderInfo = $setOrderData;
        unset($saveOrderInfo['all_electric']);
        //$tipAll = $orderDetails['tip_number'] + $orderDetails['tip_loss_number'];
        $tipAll = $orderDetails['tip_number'];
        $tipMoney = ($orderInfo['charge_cost'] + $orderInfo['service_cost']) * $tipAll;
        //$peakAll = $orderDetails['peak_number'] + $orderDetails['peak_loss_number'];
        $peakAll = $orderDetails['peak_number'];
        $peakMoney = ($orderInfo['peak_electric_cost'] + $orderInfo['peak_service_cost']) * $peakAll;
        //$flatAll = $orderDetails['flat_number'] + $orderDetails['flat_loss_number'];
        $flatAll = $orderDetails['flat_number'];
        $flatMoney = ($orderInfo['flat_electric_cost'] + $orderInfo['flat_service_cost']) * $flatAll;
        //$valleyAll = $orderDetails['valley_number'] + $orderDetails['valley_loss_number'];
        $valleyAll = $orderDetails['valley_number'];
        $valleyMoney = ($orderInfo['valley_electric_cost'] + $orderInfo['valley_service_cost']) * $valleyAll;
        $allMoney = $tipMoney + $peakMoney + $flatMoney + $valleyMoney;
        $allMoney = ceil(($allMoney * 100)) * 0.01;
        $totalPrice = bcmul($allMoney,1,2);
        //计算电费
        $getAllChargeCost = $orderInfo['charge_cost'] * $tipAll + $orderInfo['peak_electric_cost'] * $peakAll + $orderInfo['flat_electric_cost'] * $flatAll + $orderInfo['valley_electric_cost'] * $valleyAll;
        $allChargeCost = bcmul(ceil(($getAllChargeCost * 100)),0.01,2);
        //判断设备传送的金额是否大于计算的金额
        if(isset($orderDetails['consume_money']) && $orderDetails['consume_money']){
            $orderDetails['consume_money'] = bcmul(ceil(($orderDetails['consume_money'] * 100)),0.01,2);
            if($orderDetails['consume_money'] > $totalPrice) $totalPrice = $orderDetails['consume_money'];
        }
        $allServiceCost = $totalPrice - $allChargeCost;
        $saveOrderInfo['total_price'] = $totalPrice;
        $saveOrderInfo['pay_price'] = $totalPrice;
        $saveOrderInfo['all_charge_cost'] = $allChargeCost;
        $saveOrderInfo['all_service_cost'] = $allServiceCost;

        $orderMoneyData = [
            'order_id'=>$orderInfo['id'],
            'user_id'=>$orderInfo['uid'],
            'order_info_id'=>$orderDetails['id'],
            'all_electric'=>$setOrderData['all_electric'],
            'charge_time'=>$setOrderData['charge_time'],
            'charge_cost'=>$orderInfo['charge_cost'],
            'service_cost'=>$orderInfo['service_cost'],
            'tip_number'=>$orderDetails['tip_number'],
            'tip_loss_number'=>$orderDetails['tip_loss_number'],
            'tip_all'=>$tipAll,
            'tip_money'=>$tipMoney,
            'peak_electric_cost'=>$orderInfo['peak_electric_cost'],
            'peak_service_cost'=>$orderInfo['peak_service_cost'],
            'peak_number'=>$orderDetails['peak_number'],
            'peak_loss_number'=>$orderDetails['peak_loss_number'],
            'peak_all'=>$peakAll,
            'peak_money'=>$peakMoney,
            'flat_electric_cost'=>$orderInfo['flat_electric_cost'],
            'flat_service_cost'=>$orderInfo['flat_service_cost'],
            'flat_number'=>$orderDetails['flat_number'],
            'flat_loss_number'=>$orderDetails['flat_loss_number'],
            'flat_all'=>$flatAll,
            'flat_money'=>$flatMoney,
            'valley_electric_cost'=>$orderInfo['valley_electric_cost'],
            'valley_service_cost'=>$orderInfo['valley_service_cost'],
            'valley_number'=>$orderDetails['valley_number'],
            'valley_loss_number'=>$orderDetails['valley_loss_number'],
            'valley_all'=>$valleyAll,
            'valley_money'=>$valleyMoney,
            'total_price'=>$totalPrice,
            'start_time'=>$orderDetails['start_time'],
            'end_time'=>$orderDetails['end_time'],
            'create_time'=>date("Y-m-d H:i:s"),
            'order_son_id'=>isset($orderDetails['order_son_id']) ? $orderDetails['order_son_id'] : 0,
        ];
        return ['save_order_info'=>$saveOrderInfo,'order_money_data'=>$orderMoneyData];
    }

    /**
     * 设置返回的充电量
     * @param $orderInfo
     * @param $setOrderData
     * @param $orderSonInfo
     * @return array
     */
    function setElectricNumber($orderInfo,$setOrderData,$orderSonInfo){
        //获取开始时间
        $chargeTime = $setOrderData['charge_time'] * 60;
        $endTime = strtotime($orderSonInfo['create_time']);
        $startTime = $endTime - $chargeTime;
        $countTime = $startTime;
        //获取对应的收费模式
        $costContent = json_decode($orderInfo['cost_content'],true);
        $setCostInfo = [];
        foreach ($costContent as $key=>$value){
            $setCostInfo[$value['name']] = $value['value'];
        }
        $status = true;
        $tipTime = 0;
        $peakTime = 0;
        $flatTime = 0;
        $valleyTime = 0;
        while($status && $countTime < $endTime){
            $house = date("H",$countTime);
            $min = date("i",$countTime);
            //获取对应的下标
            $keyNumber = $house * 2;
            if($min >= 30){
                $keyNumber = $keyNumber + 2;
                $useMin = 60 - $min;
            }else{
                $keyNumber = $keyNumber + 1;
                $useMin = 30 - $min;
            }
            //判断是否到了结束时间
            $checkTime = $countTime + $useMin * 60;
            if($checkTime > $endTime){
                $useMin = date("i",$endTime) - $min;
                $countTime = $endTime;
                $status =false;
            }else{
                $countTime = $countTime + $useMin * 60;
            }
            $key = "model-".$keyNumber;
            if(isset($setCostInfo[$key])){
                if($setCostInfo[$key] == '00'){         //尖费率时间
                    $tipTime = $tipTime + $useMin;
                }else if($setCostInfo[$key] == '01'){   //峰费率时间
                    $peakTime = $peakTime + $useMin;
                }else if($setCostInfo[$key] == '02'){   //平费率时间
                    $flatTime = $flatTime + $useMin;
                }else if($setCostInfo[$key] == '03'){   //谷费率时间
                    $valleyTime = $valleyTime + $useMin;
                }else{
                    $peakTime = $peakTime + $useMin;
                }
            }else{
                $peakTime = $peakTime + $useMin;
            }
        }
        if($tipTime <= 0){
            $tipNumber = 0;
            $tipLossNumber = 0;
        }else{
            $tipNumber = round((bcmul(($tipTime/$setOrderData['charge_time']),$setOrderData['charge_number'],5) * 10000)) * 0.0001;
            $tipLossNumber = round((bcmul(($tipTime/$setOrderData['charge_time']),$setOrderData['loss_number'],5) * 10000)) * 0.0001;
        }
        if($peakTime <= 0){
            $peakNumber = 0;
            $peakLossNumber = 0;
        }else{
            $peakNumber = round((bcmul(($peakTime/$setOrderData['charge_time']),$setOrderData['charge_number'],5) * 10000)) * 0.0001;
            $peakLossNumber = round((bcmul(($peakTime/$setOrderData['charge_time']),$setOrderData['loss_number'],5) * 10000)) * 0.0001;
        }
        if($flatTime <= 0){
            $flatNumber = 0;
            $flatLossNumber = 0;
        }else{
            $flatNumber = round((bcmul(($flatTime/$setOrderData['charge_time']),$setOrderData['charge_number'],5) * 10000)) * 0.0001;
            $flatLossNumber = round((bcmul(($flatTime/$setOrderData['charge_time']),$setOrderData['loss_number'],5) * 10000)) * 0.0001;
        }
        if($valleyTime <= 0){
            $valleyNumber = 0;
            $valleyLossNumber = 0;
        }else{
            $valleyNumber = round((bcmul(($valleyTime/$setOrderData['charge_time']),$setOrderData['charge_number'],5) * 10000)) * 0.0001;
            $valleyLossNumber = round((bcmul(($valleyTime/$setOrderData['charge_time']),$setOrderData['loss_number'],5) * 10000)) * 0.0001;
        }
        $backData = [
            'start_time'=>date("Y-m-d H:i:s",$startTime),
            'end_time'=>$orderSonInfo['create_time'],
            'tip_number'=>$tipNumber,
            'tip_loss_number'=>$tipLossNumber,
            'peak_number'=>$peakNumber,
            'peak_loss_number'=>$peakLossNumber,
            'flat_number'=>$flatNumber,
            'flat_loss_number'=>$flatLossNumber,
            'valley_number'=>$valleyNumber,
            'valley_loss_number'=>$valleyLossNumber,
            'id'=>0,
            'order_son_id'=>$orderSonInfo['id'],
            'consume_money'=>$orderSonInfo['charged_amount'],
        ];
        return $backData;
    }

    /**
     * 订单列表，充电记录
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function pileOrderList(){
        [$page,$limit] = $this->getPage();
        $userId = $this->request->uid();
        $getData = Request::post();
        if(isset($getData['status']) && $getData['status']){
            if(in_array($getData['status'],[2,3,4,5,6])){
                $addWhere = [['status','=',$getData['status']]];
            }else{
                return $this->fail('请选择正确的状态');
            }
        }else{
            $addWhere = [['status','>',1]];
        }
        $pileOrderModel = new PileOrder();
        $field = "id,uid,order_sn,status,paid,pay_type,station_id,charge_time,charge_number,loss_number,total_price,pay_price,pay_time,create_time";
        $backData = $pileOrderModel->getUserOrderList($userId,$addWhere,$page,$limit,$field);
        $backData['user_pay_pwd'] = $this->userPayPwdStatus();
        return $this->success('获取订单成功',$backData);
    }

    /**
     * 用户是否设置支付密码
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function userPayPwdStatus(){
        $userId = $this->request->uid();
        $userModel = new User();
        $userInfo = $userModel->getUserInfoById($userId);
        if($userInfo['pay_pwd']) return 1;
        return 0;
    }

    /**
     * 订单支付
     * @return $this|Order
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     */
    function orderPay(){
        $getData = Request::post();
        if(!$getData['order_id']) return $this->fail('请选择充电记录');
        if(!isset($getData['pay_type']) || $getData['pay_type'] == '') return $this->fail('请选择支付方式');
        $payTypeList = [0,1,2,3,4];
        if(!in_array($getData['pay_type'],$payTypeList)) return $this->fail('请选择正确的支付方式');
        $pileOrderModel = new PileOrder();
        $orderInfo = $pileOrderModel->getInfoById($getData['order_id']);
        if(!$orderInfo) return $this->fail('请选择正确的充电订单');
        $userId = $this->request->uid();
        if($orderInfo['uid'] != $userId)  return $this->fail('请选择正确的充电订单');
        if($orderInfo['paid'] == 1) return $this->success('当前订单已经支付');
        if($orderInfo['status'] != 3) return $this->fail('当前订单不是处在待支付状态');
        if($getData['pay_type'] == 0){
            return $this->balancePay($getData,$orderInfo,$userId);
        //微信公众号支付
        }else if($getData['pay_type'] == 1){
            return $this->fail('当前暂不支持当前支付');
        //微信小程序支付
        }else if($getData['pay_type'] == 2){
            return $this->weChatApplePay($orderInfo,$userId);
        //微信h5支付
        }else if($getData['pay_type'] == 3){
            return $this->fail('当前暂不支持当前支付');
        //支付宝支付
        }else if($getData['pay_type'] == 4){
            return $this->fail('当前暂不支持支付宝支付');
        }else{
            return $this->fail('选择正确的支付方式');
        }

    }

    /**
     * 余额支付
     * @param $getData
     * @param $orderInfo
     * @param $userId
     * @param int $changePassword
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function balancePay($getData,$orderInfo,$userId,$changePassword = 1){
        $userModel = new User();
        $userInfo = $userModel->getUserInfoById($userId);
        if($changePassword){
            if(!isset($getData['pay_pwd']) || !$getData['pay_pwd']) return $this->fail('请输入支付密码');
            if (!password_verify($pwd = (string)$getData['pay_pwd'], $userInfo['pay_pwd'])) return $this->fail('支付密码错误');
        }
        if($userInfo['now_money'] < $orderInfo['pay_price']) return $this->fail('账户余额不足');
        $billData = [
            'link_id'=>$orderInfo['id'],
            'pm'=>0,
            'title'=>'订单支付',
            'category'=>'now_money',
            'type'=>'charge_order_pay',
            'mark'=>'充电订单支付',
        ];
        $userBillModel = new UserBill();
        Db::startTrans();
        $orderResult = $this->setPayOrder(0,$orderInfo);
        //修改用户账户
        if($orderInfo['pay_price'] <= 0){
            $userResult = true;
        }else{
            $userResult = $userModel->where('id',$userId)->dec('now_money',$orderInfo['pay_price'])->update();
        }
        //插入用户账户记录
        $userBillResult = $userBillModel->addRecord($userInfo,$orderInfo['pay_price'],$billData);
        if($orderResult && $userResult && $userBillResult){
            Db::commit();
            return $this->success('支付成功',['order_id'=>$orderInfo['id']]);
        }else{
            Db::rollback();
            return $this->fail('支付失败');
        }
    }

    /**
     * 微信小程序支付
     * @param $orderInfo
     * @param $userId
     * @return $this
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function weChatApplePay($orderInfo,$userId){
        $weChatUserModel = new WechatUser();
        $appleUserWhere = ['user_id'=>$userId,'user_type'=>'applet'];
        $weChatUser = $weChatUserModel->getInfoByWhere($appleUserWhere);
        if(!$weChatUser['routine_openid']) return $this->fail('请重新授权登录',-1);
        $notifyData = ['notify_url'=>config('add.web_url')."/index/wechat/apple/notifyUrl"];
        $weChatAppletService = new WeChatAppletService();
        $app = $weChatAppletService->payOrder();
        $orderData = [
            'body' => '订单支付',
            'out_trade_no' => $orderInfo['order_sn'],
            'total_fee' => bcmul($orderInfo['pay_price'] , 100,0),
            'notify_url' => $notifyData['notify_url'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' =>$weChatUser['routine_openid'],
        ];
        $result = $app->order->unify($orderData);
        if($result['return_code'] == 'SUCCESS'){
            $appleConfigData = $weChatAppletService->getConfig();
            $mchConfig = $weChatAppletService->mchConfig();
            $backData = [
                'appId'=>$appleConfigData['app_id'],
                'timeStamp'=>time(),
                'nonceStr'=>$result['nonce_str'],
                'package'=>'prepay_id=' .$result['prepay_id'],
                'signType'=>'MD5',
            ];
            $backData['paySign'] = generate_sign($backData,$mchConfig['mch_key']);
            return $this->success('获取成功',$backData);
        }else{
            return $this->fail('获取小程序支付失败，请稍后重试',1,400,$result);
        }
    }

    //小程序支付回调
    function weChatAppleNotify(){
        $getData = file_get_contents('php://input');
        //$getData = json_decode(Db::table('jy_pay_back_info')->where('id',14)->value('content'),true);
        Log::info('小程序支付回调'.json_encode($getData));
        $message = XML::parse($getData);
        if(empty($message)){
            $backResult = weChatAppleBack('FAIL','缺少参数');
            echo $backResult;
            exit();
        }
        //添加回调记录
        Db::table('jy_pay_back_info')->insertGetId([
            'record_id'=>0,
            'type'=>1,
            'back_type'=>1,
            'content'=>json_encode($message,JSON_UNESCAPED_UNICODE),
            'create_time'=>date("Y-m-d H:i:s"),
        ]);
        //判断返回数据通讯
        if(!isset($message['return_code']) || $message['return_code'] != 'SUCCESS'){
            $backResult = weChatAppleBack('FAIL','支付通讯错误');
            echo $backResult;
            exit();
        }
        //验签
        $weChatAppletService = new WeChatAppletService();
        $getSign = $message['sign'];
        unset($message['sign']);
        $mchConfig = $weChatAppletService->mchConfig();
        $sign = generate_sign($message,$mchConfig['mch_key']);
        //dump($message);
        //判断验签是否通过
        if($getSign == $sign ) {
            if(isset($message['result_code']) && $message['result_code'] == 'SUCCESS' && $message['time_end']){
                $orderModel = new PileOrder();
                $orderWhere = ['order_sn'=>$message['out_trade_no']];
                $orderInfo = $orderModel->getInfoByWhere($orderWhere);
                if($orderInfo){
                    //判断订单释放已经支付
                    if($orderInfo['paid'] == 1){
                        $backResult = weChatAppleBack('SUCCESS','OK');
                        echo $backResult;
                        exit();
                    }else{
                        //判断订单是不是处在待支付状态
                        if($orderInfo['status'] != 3){
                            $backResult = weChatAppleBack('FAIL','当前订单不是处在待支付状态');
                        }else{
                            //支付金额判断
                            if($message['total_fee'] >= bcmul($orderInfo['pay_price'],100,0)){
                                $orderResult = $this->setPayOrder(2,$orderInfo,$message);
                                if($orderResult){
                                    $backResult =  weChatAppleBack('SUCCESS','OK');
                                }else{
                                    $backResult = weChatAppleBack('FAIL','订单设置失败');
                                }
                            }else{
                                $backResult = weChatAppleBack('FAIL','订单金额错误');
                            }
                        }
                        echo $backResult;
                        exit();
                    }
                }else{
                    $backResult = weChatAppleBack('FAIL','没有对应的订单信息');
                }
            }else{
                $backResult = weChatAppleBack('FAIL','不是支付成功状态');
            }
        }else{
            $backResult = weChatAppleBack('FAIL','订单验签不通过');
        };
        echo $backResult;
        exit();
    }

    /**
     * 获取订单支付要设置的参数
     * @return array
     */
    function getOrderPayData($getData){
        return  [
            'paid'=>1,
            'pay_time'=>date("Y-m-h H:i:s"),
            'pay_type'=>$getData['pay_type'],
            'status'=>4,
            'is_del'=>0,
        ];
    }

    /**
     * 支付订单设置
     * @param $payType
     * @param $message
     * @param $orderInfo
     * @return static
     */
    function setPayOrder($payType, $orderInfo, $message=[]){
        $saveOrder = $this->getOrderPayData(['pay_type'=>$payType]);
        $saveOrder['third_sn'] = isset($message['transaction_id']) ? $message['transaction_id'] : '';
        $saveOrder['is_del'] = 0;
        $saveOrder['is_system_del'] = 0;
        $orderModel = new PileOrder();
        $orderResult = $orderModel->where('id',$orderInfo['id'])->update($saveOrder);
        if($orderInfo){
            $orderStatusModel = new OrderStatus();
            $statusResult = $orderStatusModel->addInfo($orderInfo,5,'用户支付订单');
        }
        return $orderResult;
    }

    /**
     * 支付列表
     * @return $this
     */
    function payTypeList(){
        $backData = [
            [
                'value'=>0,
                'title'=>'余额支付',
                'platform'=>['wechat','appH5','wechatApplet'],
                'icon'=>config('add.web_url')."/static/imgs/balance.png",
            ],
            [
                'value'=>1,
                'title'=>'微信支付',
                'platform'=>['wechat'],
                'icon'=>config('add.web_url')."/static/imgs/wechat.png",
            ],
            [
                'value'=>2,
                'title'=>'微信支付',
                'platform'=>['wechatApplet'],
                'icon'=>config('add.web_url')."/static/imgs/wechat.png",
            ],
            [
                'value'=>2,
                'title'=>'微信支付',
                'platform'=>['appH5'],
                'icon'=>config('add.web_url')."/static/imgs/wechat.png",
            ],
            [
                'value'=>4,
                'title'=>'支付宝支付',
                'platform'=>['appH5'],
                'icon'=>config('add.web_url')."/static/imgs/aliapy.png",
            ],
        ];
        return $this->success('获取成功',$backData);
    }

    /**
     * 订单金额统计定时器
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function orderMoneyTimer(){
        $orderWhere = [
            'is_del'=>0,
            'is_system_del'=>0,
            'is_verify'=>0,
            'status'=>2,
            'paid'=>0,
            'order_type'=>1,
        ];
        //截止30天
        $setTime = time() - 30 * 24 * 60 * 60;
        $list = Db::table('jy_pile_order')->where($orderWhere)
            ->where('create_time','>=',date("Y-m-d H:i:s",$setTime))->select();
        if($list){
            $list = $list->toArray();
            //dd($list);
            $systemConfigModel = new SystemConfig();
            $defaultBalancePayStatus = $systemConfigModel->getValueByKey('default_balance_pay_status');
            $pileOrderModel = new PileOrder();
            foreach ($list as $key=>$orderInfo){
                $result = $this->setOrderPayInfo($pileOrderModel,$orderInfo);
                //设置成功，进行订单支付
                if($result['code'] == 0 && $defaultBalancePayStatus){
                    $this->setOrderBalancePay($pileOrderModel,$orderInfo['id']);
                }
            }
        }
    }

    /**
     * 订单支付金额设置
     * @param $pileOrderModel
     * @param $orderInfo
     * @param string $countRemark
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function setOrderPayInfo($pileOrderModel,$orderInfo,$countRemark='定时器统计金额'){
        if($orderInfo['is_verify'] == 0 && $orderInfo['status'] >= 2){
            //充电时间、充电度数、充电损耗统计
            $orderInfoModel = new PileOrderInfo();
            $orderDetails = $orderInfoModel->getOrderInfo($orderInfo['id']);
            if(!$orderDetails) return ['code'=>1,'msg'=>'等待订单数据确认'];
            $orderSonModel = new PileOrderSon();
            $orderSonList = $orderSonModel->getLastOrderSonList($orderInfo['id'],1,2);
            $infoTimeCount = strtotime($orderDetails['end_time']) - strtotime($orderDetails['start_time']);
            $infoTimeCount = bcdiv($infoTimeCount,60,2);
            //$infoElectric = $orderDetails['all_electric'] + $orderDetails['all_loss_electric'];
            $infoElectric = $orderDetails['all_electric'];
            $setOrderData = ['status'=>3,'update_time'=>date("Y-m-d H:i:s"),'is_verify'=>1];
            //存在着对应的充电记录
            if(isset($orderSonList[0])){
                $sonTimeCount = $orderSonList[0]['charge_time'];
                //$sonElectric = $orderSonList[0]['charge_number'] + $orderSonList[0]['loss_number'];
                $sonElectric = $orderSonList[0]['charge_number'];
                $getSonInfo = json_decode($orderSonList[0]['content_data'],true);
                $changeElectric = 0;
                if($orderSonList[0]['type'] == 1){
                    $changeElectric = $getSonInfo['out_voltage'] * $getSonInfo['out_electric'] * 10 * 20;
                }else if($orderSonList[0]['type'] == 2){
                    $changeElectric = $getSonInfo['pile_voltage_out'] * $getSonInfo['pile_electric_out'] * 10 * 20;
                }
                $differenceElectric = $infoElectric - $sonElectric;
                //交易数据正常 结算记录的充电的总电量大于上条记录的总电流
                if($changeElectric > 0 && $infoElectric > $sonElectric && $differenceElectric < $changeElectric){
                    if($sonTimeCount > $infoTimeCount) $infoTimeCount = $sonTimeCount;
                    $setOrderData['all_electric'] = $infoElectric;//总的充电电量
                    $setOrderData['charge_number'] = $orderDetails['all_electric'];//充电电量
                    $setOrderData['loss_number'] = $orderDetails['all_loss_electric'];//计损总电量
                    $setOrderData['charge_time'] = $infoTimeCount;//总的充电时间
                    //统计订单的金额
                    $getMoneyInfo = $this->countOrderMoney($orderInfo,$orderDetails,$setOrderData);
                    //交易数据未达到指定的条件
                }else{
                    if(isset($orderSonList[1])){
                        //第二条记录的充电时间大于第一条
                        if($sonTimeCount < $orderSonList[1]['charge_time']) $sonTimeCount = $orderSonList[1]['charge_time'];
                        //第二条的充电总量大于第一条
                        if($sonElectric < ($orderSonList[1]['charge_number'] + $orderSonList[1]['loss_number'])){
                            //$sonElectric = $orderSonList[1]['charge_number'] + $orderSonList[1]['loss_number'];
                            $sonElectric = $orderSonList[1]['charge_number'];
                            $orderSonList[0]['charge_number'] = $orderSonList[1]['charge_number'];
                            $orderSonList[0]['loss_number'] = $orderSonList[1]['loss_number'];
                        }
                        if($orderSonList[0]['charged_amount'] < $orderSonList[1]['charged_amount']){
                            $orderSonList[0]['charged_amount'] = $orderSonList[1]['charged_amount'];
                        }
                    }
                    $setOrderData['all_electric'] = $sonElectric;//总的充电电量
                    $setOrderData['charge_number'] = $orderSonList[0]['charge_number'];//充电电量
                    $setOrderData['loss_number'] = $orderSonList[0]['loss_number'];//计损总电量
                    $setOrderData['charge_time'] = $sonTimeCount;//总的充电时间
                    //统计订单的金额
                    $setOrderDetails = $this->setElectricNumber($orderInfo,$setOrderData,$orderSonList[0]);
                    $getMoneyInfo = $this->countOrderMoney($orderInfo,$setOrderDetails,$setOrderData);
                }
            }else{
                $setOrderData['all_electric'] = $infoElectric;//总的充电电量
                $setOrderData['charge_number'] = $orderDetails['all_electric'];//充电总电量
                $setOrderData['loss_number'] = $orderDetails['all_loss_electric'];//计损总电量
                $setOrderData['charge_time'] = $infoTimeCount;//总的充电时间
                //统计订单的金额
                $getMoneyInfo = $this->countOrderMoney($orderInfo,$orderDetails,$setOrderData);
            }
            //判断是否开启指定用户单独统计金额
            $systemConfigModel = new SystemConfig();
            $payUserCostStatus = $systemConfigModel->getValueByKey('pay_order_user_cost_status');
            $addCountRemark = '';
            if($payUserCostStatus){
                $userPileCostModel = new UserPileCost();
                $costWhere = ['user_id'=>$orderInfo['uid'],'is_status'=>1,'is_delete'=>1,'station_id'=>$orderInfo['station_id'],'pile_id'=>$orderInfo['pile_id']];
                $userCost = $userPileCostModel->getUserCostInfo($costWhere);
                if($userCost){
                    $getMoneyInfo['save_order_info']['pay_price'] = bcmul($getMoneyInfo['save_order_info']['all_electric'] ,$userCost['cost_electricity'],2) + bcmul($getMoneyInfo['save_order_info']['all_electric'] ,$userCost['cost_number'],2);
                    $addCountRemark = '--使用用户费率进行统计';
                    $getMoneyInfo['save_order_info']['user_cost_id'] = $userCost['id'];
                }
            }

            $PileOrderMoney = new PileOrderMoney();
            Db::startTrans();
            $orderResult = $pileOrderModel->updateOrder($orderInfo['id'],$getMoneyInfo['save_order_info']);
            $getMoneyInfo['order_money_data']['remark'] = $countRemark.$addCountRemark;
            $orderMoneyResult = $PileOrderMoney->addInfo($getMoneyInfo['order_money_data']);
            if($orderResult && $orderMoneyResult){
                Db::commit();
                return ['code'=>0,'msg'=>'订单金额统计成功'];
            }else{
                Db::rollBack();
                return ['code'=>1,'msg'=>'等待订单数据确认'];
            }
        }else{
            return ['code'=>0,'msg'=>'订单金额已经设置'];
        }
    }

    /**
     * 订单默认余额支付
     * @param $pileOrderModel
     * @param $orderId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function setOrderBalancePay($pileOrderModel,$orderId){
        $where = ['is_del'=>0, 'is_system_del'=>0,'order_type'=>1,];
        $orderInfo = $pileOrderModel->getInfoById($orderId,$where);
        //存在订单，未支付且已经统计
        if($orderInfo && $orderInfo['paid'] == 0 && $orderInfo['status'] == 3){
            $userModel = new User();
            $userInfo = $userModel->getUserInfoById($orderInfo['uid']);
            if($userInfo['now_money'] < $orderInfo['pay_price']) return ['code'=>1,'msg'=>'账户余额不足'];
            $billData = [
                'link_id'=>$orderInfo['id'],
                'pm'=>0,
                'title'=>'订单支付',
                'category'=>'now_money',
                'type'=>'charge_order_pay',
                'mark'=>'充电订单支付',
            ];
            $userBillModel = new UserBill();
            Db::startTrans();
            $orderResult = $this->setPayOrder(0,$orderInfo);
            //修改用户账户
            if($orderInfo['pay_price'] <= 0){
                $userResult = true;
            }else{
                $userResult = $userModel->where('id',$orderInfo['uid'])->dec('now_money',$orderInfo['pay_price'])->update();
            }
            //插入用户账户记录
            $userBillResult = $userBillModel->addRecord($userInfo,$orderInfo['pay_price'],$billData);
            if($orderResult && $userResult && $userBillResult){
                Db::commit();
                return ['code'=>0,'msg'=>'支付成功'];
            }else{
                Db::rollback();
                return ['code'=>1,'msg'=>'支付失败'];
            }
        }
    }

    //获取指定充电桩订单
    function pileOrder(){
        $getData = Request::post();
        [$page,$limit] = $this->getPage();
        if(!$getData['pile_id']) return $this->fail('请选择充电桩');
        $pileOrderModel = new PileOrder();
        $where = ['is_del'=>0,'is_system_del'=>0,'status'=>4,'pile_id'=>$getData['pile_id'],'paid'=>1];
        $field = "id,uid,order_sn,status,paid,pay_type,station_id,charge_time,charge_number,loss_number,total_price,pay_price,pay_time,create_time,start_time,end_time,all_charge_cost,all_service_cost";
        $getInfo = $pileOrderModel->getOrderListByWhere($where,$page,$limit,$field);
        return $this->success('获取成功',$getInfo);
    }

    /**
     * 获取用户是否有充电订单
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function chargeOrderStatus(){
        $userId = $this->getLogUserId();
        if(!$userId) return $this->fail('用户暂未登录');
        $pileOrderModel = new PileOrder();
        $checkInfo = $pileOrderModel->checkChargeOrder($userId);
        if(!$checkInfo) return $this->fail('暂无充电订单');
        $backData = ['order_id'=>$checkInfo['id'],'pile_id'=>$checkInfo['pile_id'],'gun_id'=>$checkInfo['gun_id']];
        return $this->success('存在充电订单',$backData);
    }
    function dianzhuanglist(){
        $userId = $this->getLogUserId();
        $list = Db::table('jy_danzhuang')->where('uid',$userId)->select()->toArray();


        $array['count'] = count($list);
        $yesterdayStart = date("Y-m-d 00:00:00", strtotime("-1 day"));
        $yesterdayEnd = date("Y-m-d 23:59:59", strtotime("-1 day"));
        $total_price = 0;
        $ele_price = 0;
        $servers_price = 0;
        foreach ($list as &$item){
            $total_price += Db::table('jy_charge_ykc_order')->where('charge_terminal',$item['dzname'])->sum('total_price');
            $ele_price += Db::table('jy_charge_ykc_order')->where('charge_terminal',$item['dzname'])->sum('ele_price');
            $servers_price += Db::table('jy_charge_ykc_order')->where('charge_terminal',$item['dzname'])->sum('servers_price');
            $item['zuori'] = Db::table('jy_charge_ykc_order')
                ->where('charge_terminal', $item['dzname'])
                ->whereBetween('order_end_time', [$yesterdayStart, $yesterdayEnd])
                ->sum('total_price');
            $item['total_price'] = Db::table('jy_charge_ykc_order')
                ->where('charge_terminal', $item['dzname'])
                ->sum('total_price');
        }
        $array['total_price'] = $total_price;
        $array['ele_price'] = $ele_price;
        $array['servers_price'] = $servers_price;

        $array['data'] = $list;


        return $this->success('电桩列表',$array);
    }
    function dianzhuang(){
        $getData = Request::post();
        $list = Db::table('jy_charge_ykc_order')
            ->where('charge_terminal', $getData['id'])
            ->select()->toArray();
        for($i=0;$i<count($list);$i++){
            $dateTime1 = new \DateTime($list[$i]['beg_time']);
            $dateTime2 = new \DateTime($list[$i]['end_time']);
            $interval = $dateTime1->diff($dateTime2);
            $list[$i]['is_time'] = $interval->format('%h时-%i分-%s秒');
        }
        return $this->success('电桩详情列表',$list);
    }

}
